package com.jiangnan.warehouse_management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiangnan.warehouse_management.common.exception.BusinessException;
import com.jiangnan.warehouse_management.dto.request.InventoryCheckRequest;
import com.jiangnan.warehouse_management.dto.response.InventoryQueryResponse;
import com.jiangnan.warehouse_management.dto.response.InventoryResponse;
import com.jiangnan.warehouse_management.dto.response.InventoryWarningListResponse;
import com.jiangnan.warehouse_management.dto.response.InventoryWarningResponse;
import com.jiangnan.warehouse_management.dto.response.InventoryStatsResponse;
import com.jiangnan.warehouse_management.mapper.InventoryMapper;
import com.jiangnan.warehouse_management.mapper.ItemMapper;
import com.jiangnan.warehouse_management.mapper.WarehouseMapper;
import com.jiangnan.warehouse_management.pojo.Inventory;
import com.jiangnan.warehouse_management.pojo.Item;
import com.jiangnan.warehouse_management.pojo.Warehouse;
import com.jiangnan.warehouse_management.service.InventoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class InventoryServiceImpl implements InventoryService {

    private final InventoryMapper inventoryMapper;
    private final ItemMapper itemMapper;
    private final WarehouseMapper warehouseMapper;

    @Override
    public InventoryQueryResponse getInventoryList(
            Integer page,
            Integer pageSize,
            Integer itemId,
            Integer warehouseId,
            Boolean lowStock) {
        
        // 参数校验和默认值设置
        page = (page == null || page < 1) ? 1 : page;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;

        // 构建查询条件
        LambdaQueryWrapper<Inventory> queryWrapper = new LambdaQueryWrapper<>();
        if (itemId != null) {
            queryWrapper.eq(Inventory::getItemId, itemId);
        }
        if (warehouseId != null) {
            queryWrapper.eq(Inventory::getWarehouseId, warehouseId);
        }
        if (Boolean.TRUE.equals(lowStock)) {
            // 使用子查询查找库存低于最小库存的记录
            queryWrapper.exists(
                "SELECT 1 FROM item i WHERE i.item_id = inventory.item_id AND inventory.quantity <= i.minimum_stock"
            );
        }

        // 开启分页
        PageHelper.startPage(page, pageSize, true);
        
        // 执行查询
        List<Inventory> inventories = inventoryMapper.selectList(queryWrapper);
        
        // 获取分页信息
        PageInfo<Inventory> pageInfo = new PageInfo<>(inventories);

        // 转换为响应对象
        List<InventoryResponse> responses = inventories.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());

        // 构建返回结果
        InventoryQueryResponse response = new InventoryQueryResponse();
        response.setList(responses);
        response.setTotal(pageInfo.getTotal());
        response.setPage(page);
        response.setPageSize(pageSize);

        return response;
    }

    @Override
    public InventoryResponse getInventoryById(Integer id) {
        // 参数校验
        if (id == null) {
            throw new BusinessException(400, "库存记录ID不能为空");
        }

        // 查询库存记录
        Inventory inventory = inventoryMapper.selectById(id);
        if (inventory == null) {
            throw new BusinessException(404, "库存记录不存在");
        }

        // 转换为响应对象
        return convertToResponse(inventory);
    }

    @Override
    @Transactional
    public Inventory checkInventory(Integer id, InventoryCheckRequest request) {
        // 参数校验
        if (id == null) {
            throw new BusinessException(400, "库存记录ID不能为空");
        }

        // 查询库存记录
        Inventory inventory = inventoryMapper.selectById(id);
        if (inventory == null) {
            throw new BusinessException(404, "库存记录不存在");
        }

        // 更新库存信息
        inventory.setQuantity(request.getQuantity());
        inventory.setLastCheckTime(new Timestamp(System.currentTimeMillis()));
        
        // 重新计算总价值
        if (inventory.getUnitPrice() != null) {
            inventory.setTotalValue(inventory.getUnitPrice() * request.getQuantity());
        }

        // 保存更新
        int rows = inventoryMapper.updateById(inventory);
        if (rows != 1) {
            throw new BusinessException(500, "更新库存记录失败");
        }

        // 返回更新后的记录
        return inventoryMapper.selectById(id);
    }

    @Override
    public InventoryWarningListResponse getInventoryWarnings() {
        List<Inventory> inventories = inventoryMapper.selectList(null);
        List<InventoryWarningResponse> warningList = inventories.stream().map(inventory -> {
            InventoryWarningResponse resp = new InventoryWarningResponse();
            resp.setInventoryId(inventory.getInventoryId());
            resp.setItemId(inventory.getItemId());
            resp.setWarehouseId(inventory.getWarehouseId());
            resp.setQuantity(inventory.getQuantity());

            // 物品信息
            Item item = itemMapper.selectById(inventory.getItemId());
            if (item != null) {
                InventoryWarningResponse.ItemDTO itemDTO = new InventoryWarningResponse.ItemDTO();
                itemDTO.setItemId(item.getItemId());
                itemDTO.setItemName(item.getItemName());
                itemDTO.setMinimumStock(item.getMinimumStock());
                itemDTO.setMaximumStock(item.getMaximumStock());
                resp.setItem(itemDTO);
            }
            // 仓库信息
            Warehouse warehouse = warehouseMapper.selectById(inventory.getWarehouseId());
            if (warehouse != null) {
                InventoryWarningResponse.WarehouseDTO warehouseDTO = new InventoryWarningResponse.WarehouseDTO();
                warehouseDTO.setWarehouseId(warehouse.getWarehouseId());
                warehouseDTO.setWarehouseName(warehouse.getWarehouseName());
                resp.setWarehouse(warehouseDTO);
            }
            // 预警级别
            String warningLevel = "normal";
            if (item != null) {
                if (inventory.getQuantity() < item.getMinimumStock()) {
                    warningLevel = "low";
                } else if (item.getMaximumStock() != null && inventory.getQuantity() > item.getMaximumStock()) {
                    warningLevel = "high";
                }
            }
            resp.setWarningLevel(warningLevel);
            return resp;
        }).toList();
        InventoryWarningListResponse response = new InventoryWarningListResponse();
        response.setList(warningList);
        return response;
    }

    @Override
    public InventoryStatsResponse getInventoryStats() {
        // 查询所有库存
        List<Inventory> inventories = inventoryMapper.selectList(null);
        // 统计不同物品和仓库
        long totalItems = inventories.stream().map(Inventory::getItemId).distinct().count();
        long totalWarehouses = inventories.stream().map(Inventory::getWarehouseId).distinct().count();
        int totalQuantity = inventories.stream().mapToInt(inv -> inv.getQuantity() == null ? 0 : inv.getQuantity()).sum();
        double totalValue = inventories.stream().mapToDouble(inv -> inv.getTotalValue() == null ? 0.0 : inv.getTotalValue()).sum();
        int lowStockItems = 0;
        int highStockItems = 0;
        for (Inventory inv : inventories) {
            Item item = itemMapper.selectById(inv.getItemId());
            if (item != null) {
                if (inv.getQuantity() != null && inv.getQuantity() < item.getMinimumStock()) {
                    lowStockItems++;
                } else if (item.getMaximumStock() != null && inv.getQuantity() != null && inv.getQuantity() > item.getMaximumStock()) {
                    highStockItems++;
                }
            }
        }
        InventoryStatsResponse resp = new InventoryStatsResponse();
        resp.setTotalItems((int) totalItems);
        resp.setTotalWarehouses((int) totalWarehouses);
        resp.setTotalQuantity(totalQuantity);
        resp.setTotalValue(totalValue);
        resp.setLowStockItems(lowStockItems);
        resp.setHighStockItems(highStockItems);
        return resp;
    }

    private InventoryResponse convertToResponse(Inventory inventory) {
        InventoryResponse response = new InventoryResponse();
        BeanUtils.copyProperties(inventory, response);

        // 设置物品信息
        Item item = itemMapper.selectById(inventory.getItemId());
        if (item != null) {
            InventoryResponse.ItemDTO itemDTO = new InventoryResponse.ItemDTO();
            itemDTO.setItemId(item.getItemId());
            itemDTO.setItemName(item.getItemName());
            itemDTO.setSpecification(item.getSpecification());
            itemDTO.setUnit(item.getUnit());
            itemDTO.setMinimumStock(item.getMinimumStock());
            itemDTO.setMaximumStock(item.getMaximumStock());
            response.setItem(itemDTO);
        }

        // 设置仓库信息
        Warehouse warehouse = warehouseMapper.selectById(inventory.getWarehouseId());
        if (warehouse != null) {
            InventoryResponse.WarehouseDTO warehouseDTO = new InventoryResponse.WarehouseDTO();
            warehouseDTO.setWarehouseId(warehouse.getWarehouseId());
            warehouseDTO.setWarehouseName(warehouse.getWarehouseName());
            warehouseDTO.setLocation(warehouse.getLocation());
            response.setWarehouse(warehouseDTO);
        }

        // 设置平均价格
        if (inventory.getQuantity() != null && inventory.getQuantity() > 0) {
            response.setAveragePrice(inventory.getTotalValue() / inventory.getQuantity());
        }

        return response;
    }
} 